<template>
  <div class="planvisit-main guanwang-bg" style="
  height: calc(100vh - 124px);border-radius: 10px"
       v-loading="loading"
       element-loading-text="访问计划获取中...">
    <div :style="{paddingTop:100 * (10 / screensStore.bodyHeight) + 'vh',
    paddingLeft:100 * (10 / screensStore.bodyWidth) + 'vw',paddingRight:100 * (10 / screensStore.bodyWidth) + 'vw',
    marginBottom:100 * (10 / screensStore.bodyHeight) + 'vh'}"
         v-if="isEmpty">
      <div class="title-desp">{{ screensStore.selPeriodObj.periodName }}</div>
      <div style="margin-top: 20px">
        <el-form :inline="true" :model="searchData" class="demo-form-inline" style="width: 100%">
          <el-form-item>
            <el-tag
              type="primary"
              effect="dark"
              round
            >
              排班明细表
            </el-tag>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchData.state" placeholder="请选择状态" style="width: 200px">
              <el-option label="全部" value="全部" />
              <el-option label="待执行" value="待执行" />
              <el-option label="执行中" value="执行中" />
              <el-option label="已完成" value="已完成" />
              <el-option label="未执行" value="未执行" />
            </el-select>
          </el-form-item>
          <el-form-item label="计划访问开始时间">
            <el-date-picker
              v-model="searchData.planStartTime"
              type="date"
              placeholder="请选择访问日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="计划访问结束时间">
            <el-date-picker
              v-model="searchData.planEndTime"
              type="date"
              placeholder="请选择结束时间"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="访问员名称">
            <el-input v-model="searchData.staffName" placeholder="请输入访问员名称" />
          </el-form-item>
          <el-form-item label="网点简称">
            <el-input v-model="searchData.outletsName" placeholder="请输入网点简称" />
          </el-form-item>
          <el-form-item label="省市区">
            <el-cascader
              :options="screensStore.proviceList"
              v-model="searchData.addressList"
              :props="{value:'label'}"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearchList"><el-icon><Search /></el-icon>查询</el-button>
            <el-button @click="onClearList"><el-icon><Refresh /></el-icon>重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: flex-end">
        <down-table-show-sort :tablePropsArr="tablePropsArr"
                              @throwTableProps="getTablePropsList"></down-table-show-sort>
      </div>
      <div>
        <el-table :data="tableData" border style="width: 100%" :tooltip-formatter="tableRowFormatter"
                  :header-cell-style="{ background: 'rgb(250,250,250)'}">
          <el-table-column label="序号" type="index" :index="indexMethod" width="80px" align="center" fixed="left" />
          <!--          <el-table-column prop="state" label="状态" align="center" width="120px" />-->
          <template v-for="item in tablePropsArr">
            <el-table-column :prop="item.prop" :label="item.label" align="center"
                             :key="item.prop" :width="item?.width ?  item?.width : 'auto'" v-if="item.isHidden"
                             :fixed="item?.fixed">
              <template #default="scope">
                <div v-if="item.prop == 'state'">
                  <el-tag
                    v-if="scope.row.state == '待执行'"
                    type="primary"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == '执行中'"
                    type="warning"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == '已完成'"
                    type="success"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == '未执行'"
                    type="info"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else
                    type="primary"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                </div>
                <div v-else>
                  <el-tooltip
                    class="box-item"
                    effect="light"
                    :content="scope.row[item.prop]"
                    placement="top"
                  >
                    <div class="text-overflow">
                      {{ scope.row[item.prop] }}
                    </div>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </template>
          <el-table-column prop="handle" label="操作" align="center" width="180px" fixed="right">
            <template #default="scope">
              <el-button type="primary" link v-if="scope.row.state == '已完成' || scope.row.state == '执行中'"
                         @click="openInputDrawer(0,scope.row)">查看
              </el-button>
              <el-button type="primary" link v-if="scope.row.state == '待执行'"
                         @click="openInputDrawer(1,scope.row)">录入
              </el-button>
              <el-button type="primary" link
                         v-if="(screensStore.selPeriodObj.state == '已完成' && scope.row.state == '已完成' &&
            (screensStore.roles.findIndex(item => item == 'staff') != -1)) && (!scope.row.tradeState || scope.row.tradeState == '审核拒绝')"
                         @click="shengqing(scope.row)">申请费用
              </el-button>
              <el-button type="primary" link v-if="scope.row.tradeState == '审核拒绝' && scope.row.tradeRemark"
                         @click="viewJujue(scope.row)">费用拒绝原因
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="fixed-row" style="width: 100%;justify-content: center;margin-top: 10px">
          <el-pagination background layout="sizes,prev,pager,next,jumper,total" :total="paging.total"
                         @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <div v-else style="width: 100%;height: 100%">
      <el-empty description="请先选择期次">
        <el-button type="primary" @click="toIssueselect">选择期次</el-button>
      </el-empty>
    </div>

    <el-drawer
      v-model="inputDrawer"
      title="访问信息"
      size="70%"
      v-loading="formLoading"
      element-loading-text="信息提交中..."
      class="jihua-submit"
      :append-to-body="true"
    >

      <el-form ref="refForm" :model="formData" :rules="formDataRules">
        <el-descriptions
          class="margin-top"
          :title="formData?.questionnaireName"
          :column="2"
          border
        >
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>网点编号</div>
            </template>
            {{ formData?.outletsCode }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>调查员编号</div>
            </template>
            {{ formData?.phone }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>地区</div>
            </template>
            {{ formData?.provinceName }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>调查结果</div>
            </template>
            <el-form-item prop="checkResult">
              <el-select placeholder="请选择调查结果" v-model="formData.checkResult" clearable
                         :disabled="!inputType">
                <el-option label="成功" value="成功"></el-option>
                <el-option label="不成功-关门" value="不成功-关门"></el-option>
                <el-option label="不成功-装修" value="不成功-装修"></el-option>
                <el-option label="不成功-搬迁" value="不成功-搬迁"></el-option>
                <el-option label="不成功-拆迁" value="不成功-拆迁"></el-option>
                <el-option label="不成功-找不到" value="不成功-找不到"></el-option>
                <el-option label="不成功-其他" value="不成功-其他"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>城市</div>
            </template>
            {{ formData?.cityName }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>不成功原因</div>
            </template>
            <el-form-item>
              <el-input clearable v-model="formData.failReason"
                        :disabled="formData.checkResult == '成功' || !inputType"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>被访店名称</div>
            </template>
            {{ formData?.outletsName }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>被访店地址</div>
            </template>
            {{ formData?.provinceName + formData?.cityName + (formData?.areaName || '') + (formData?.address || '') }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>访店日期</div>
            </template>
            <el-form-item prop="visitTime">
              <el-date-picker
                :disabled="!inputType"
                v-model="formData.visitTime"
                type="date"
                style="width: 100%"
                placeholder="请选择访店日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>天气情况</div>
            </template>
            <el-form-item prop="weather">
              <el-select placeholder="请选择天气情况" v-model="formData.weather" clearable :disabled="!inputType">
                <el-option label="晴天" value="晴天"></el-option>
                <el-option label="多云" value="多云"></el-option>
                <el-option label="阴天" value="阴天"></el-option>
                <el-option label="下雨" value="下雨"></el-option>
                <el-option label="下雪" value="下雪"></el-option>
                <el-option label="雾霾" value="雾霾"></el-option>
                <el-option label="冰雹" value="冰雹"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>入店时间</div>
            </template>
            <el-form-item prop="enterTime">
              <el-date-picker
                v-model="formData.enterTime"
                type="datetime"
                placeholder="请选择入店时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="!inputType"
                style="width: 100%"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>离店时间</div>
            </template>
            <el-form-item prop="leaveTime">
              <el-date-picker
                v-model="formData.leaveTime"
                type="datetime"
                placeholder="请选择离店时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="!inputType"
                style="width: 100%"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label"
          v-if="formData.state == '已完成'">
            <template #label>
              <div>最终总得分</div>
            </template>
            <el-tag
              type="danger"
              effect="dark"
            >
              {{  formData.score || 0 }}分
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>

      <!--      渲染问卷-->
<!--      http://192.168.31.239:8082/-->
<!--      http://129.211.212.235:3005/-->
      <WuJie name="wenjuan" url="http://129.211.212.235:3005/"></WuJie>
      <template #footer>
        <div style="width: 100%;justify-content: space-between;background: #fff" class="fixed-row">
          <div>
            <el-button type="primary" @click="openFlow">流程查看</el-button>
          </div>
          <div>
            <el-button type="primary" @click="saveSubmit(0)" v-if="!formData.state">保存</el-button>
            <el-button type="primary" v-if="!formData.state" @click="saveSubmit(1)">提交</el-button>
            <el-button @click="inputDrawer = false">返回</el-button>
          </div>
        </div>
      </template>
    </el-drawer>
    <flowview ref="refFlowview" :visitPlanId="formData.id" isType="1"></flowview>
  </div>
</template>
<script lang="ts" setup>
  import { screenStore } from '~/stores/modules/screen'
  import { nextTick, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { getPlanvisitList, saveForm, submitAuditForm, jianUpdateForm,updatePlaivist,feiyongShen } from '~/api/planvisit'
  import { setTableLocail, getTableLocail } from '~/api/public'

  let periodId = ''
  let fangwenId = ''
  const screensStore = screenStore()
  const loading = ref(false)
  const formLoading = ref(false)
  const route = useRoute()
  const router = useRouter()
  const isEmpty = ref(false)
  const refForm = ref()
  const formUpdate = ref(false)
  const refFlowview = ref()
  const tableData = ref([])
  const inputType = ref(1)
  const tablePropsArr = ref([
    {
      prop: 'state',
      label: '状态',
      width: '120px',
      isHidden: true,
      fixed:'left'
    },
    {
      prop: 'staffName',
      label: '访问员名称',
      width: 150,
      isHidden: true
    },
    {
      prop: 'outletsCode',
      label: '网点编号',
      width: 200,
      isHidden: true
    },
    {
      prop: 'outletsName',
      label: '网点简称',
      width: 200,
      isHidden: true
    },
    {
      prop: 'questionnaireTitle',
      label: '问卷名称',
      isHidden: true,
      width: 300
    },
    {
      prop:'provinceName',
      label:'省份',
      isHidden:true,
      width: 180
    },
    {
      prop:'cityName',
      label: '城市',
      isHidden:true,
      width: 180
    },
    {
      prop:'areaName',
      label:'区县',
      isHidden:true,
      width: 180
    },
    {
      prop:'address',
      label:'地址',
      isHidden:true,
      width: 300,
    },
    {
      prop: 'planStartTime',
      label: '计划访问时间',
      width: 180,
      isHidden: true
    },
    {
      prop: 'planEndTime',
      width: 180,
      label: '计划结束时间',
      isHidden: true
    }
  ])
  const formData = reactive({
    periodId: '',
    checkResult: '',
    failReason: '',
    visitTime: '',
    weather: '',
    enterTime: '',
    leaveTime: ''
  })
  const formDataRules = {
    checkResult: [{ required: true, message: '请选择调查结果', trigger: 'change' }],
    visitTime: [{ required: true, message: '请选择访店日期', trigger: 'change' }],
    enterTime: [{ required: true, message: '请选择入店时间', trigger: 'change' }],
    leaveTime: [{ required: true, message: '请选择离店时间', trigger: 'change' }]
  }
  const inputDrawer = ref(false)
  const paging = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })
  const searchData = reactive({
    state: '',
    planStartTime: '',
    planEndTime: '',
    staffName: '',
    addressList:[],
    outletsName:'',
  })
  onMounted(() => {
    if (route.query.periodId) {
      isEmpty.value = true
      periodId = route.query.periodId
      getTableList()
    } else {
      isEmpty.value = false
    }

    getTableLocail('planvisit').then(res => {
      if (res.code == 200) {
        tablePropsArr.value = JSON.parse(res.data.fieldJson)
      } else {
        tablePropsArr.value = [
          {
            prop: 'state',
            label: '状态',
            width: '120px',
            isHidden: true,
          },
          {
            prop: 'staffName',
            label: '访问员名称',
            isHidden: true
          },
          {
            prop: 'outletsCode',
            label: '网点编号',
            width: 200,
            isHidden: true
          },
          {
            prop: 'outletsName',
            label: '网点简称',
            width: 200,
            isHidden: true
          },
          {
            prop: 'questionnaireTitle',
            label: '问卷名称',
            isHidden: true,
            width: 300
          },
          {
            prop:'provinceName',
            label:'省份',
            isHidden:true,
            width: 180
          },
          {
            prop:'cityName',
            label: '城市',
            isHidden:true,
            width: 180
          },
          {
            prop:'areaName',
            label:'区县',
            isHidden:true,
            width: 180
          },
          {
            prop:'address',
            label:'地址',
            isHidden:true,
            width: 300,
          },
          {
            prop: 'planStartTime',
            label: '计划访问时间',
            isHidden: true
          },
          {
            prop: 'planEndTime',
            label: '计划结束时间',
            isHidden: true
          }
        ]
      }
    })
  })
  const viewJujue = (row) => {
    ElMessageBox.alert(`${row.tradeRemark}`, '费用拒绝原因', {
      confirmButtonText: '确认',
    })
  }
  const getTablePropsList = (tablePropsArrs) => {
    tablePropsArr.value = tablePropsArrs
    const data = {
      name: 'planvisit',
      fieldJson: JSON.stringify(tablePropsArr.value)
    }
    setTableLocail(data)
  }
  const shengqing = (row) => {
    ElMessageBox.confirm(
      '是否确认申请费用？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        feiyongShen(row.id).then(res => {
          if(res.code == 200){
            ElMessage.success('费用申请成功')
            getTableList()
          }
          else{
            ElMessage.error(res.msg || '费用申请失败')
          }
        })
      })
  }
  const tableRowFormatter = (data) => {
    return `${data.cellValue}`
  }

  function onSearchList() {
    if(searchData.addressList.length){
      searchData.provinceName = searchData.addressList[0]
      searchData.cityName = searchData.addressList[1]
      searchData.areaName = searchData.addressList[2]
    }
    else{
      searchData.provinceName = ''
      searchData.cityName = ''
      searchData.areaName = ''
    }
    paging.currentPage = 1
    getTableList()
  }

  function onClearList() {
    Object.assign(searchData, {
      state: '',
      planStartTime: '',
      planEndTime: '',
      staffName: '',
      outletsName: '',
      provinceName:'',
      cityName:'',
      areaName:'',
      addressList: []
    })
    paging.currentPage = 1
    getTableList()
  }

  function handleSizeChange(val) {
    paging.pageSize = val
    getTableList()
  }

  function handleCurrentChange(val) {
    paging.currentPage = val
    getTableList()
  }

  function indexMethod(index: number) {
    return (paging.currentPage - 1) * paging.pageSize + index + 1
  }

  // 去往期次选择页面
  function toIssueselect() {
    screensStore.activeHomeNav = '期次选择'
    router.replace({ path: '/issueselect' })
  }

  function getTableList() {
    loading.value = true
    const params = {
      ...searchData,
      periodId,
      current: paging.currentPage,
      size: paging.pageSize
    }
    delete params.addressList
    getPlanvisitList(params).then(res => {
      loading.value = false
      if (res.code == 200) {
        tableData.value = res.data.records
        paging.total = res.data.total * 1
      } else {
        tableData.value = []
        paging.total = 0
      }
    }).catch(() => {
      loading.value = false
    })
  }

  const wenjuanJson = ref('')

  function openInputDrawer(type, row) {
    loading.value = true
    inputType.value = type
    Object.assign(formData, {
      ...row
    })
    formUpdate.value = false
    delete formData.state
    formData.periodId = periodId
    formData.schedulingTaskId = row.id
    jianUpdateForm(row.id).then(res => {
      loading.value = false
      if (res.code == 200) {
        if (res.data.id) {
          Object.assign(formData, {
            ...res.data
          })
          formUpdate.value = true
        }
        else{
          formData.id = ''
        }
        inputDrawer.value = true
        try{
          if (!res.data.questJson) {
            wenjuanJson.value = ''
          } else {
            wenjuanJson.value = JSON.parse(res.data.questJson)
          }
        }catch (e) {
        }
        nextTick(() => {
          if (window.document.querySelector('iframe[name=wenjuan]').contentWindow.setWenJsonValue) {
            setTimeout(()=>{
              window.document.querySelector('iframe[name=wenjuan]').contentWindow.setWenJsonValue(wenjuanJson.value, formData.state ? 'yulan' : 'xiezuo',
              'yulan',screensStore.roles)
            },1000)
          } else {
            setTimeout(() => {
              window.document.querySelector('iframe[name=wenjuan]').contentWindow.setWenJsonValue(wenjuanJson.value, formData.state ? 'yulan' : 'xiezuo',
                'yulan',screensStore.roles)
            }, 1000)
          }
        })

      } else {
        inputDrawer.value = true
        formUpdate.value = false
      }
    }).catch(() => {
      loading.value = false
    })
  }

  function openFlow() {
    refFlowview.value.openFlowDrawer()
  }

  function saveSubmit(type) {
    // 验证问卷必填
    window.document.querySelector('iframe[name=wenjuan]').contentWindow.getWenJuanValue().then(async result => {
      await refForm.value.validate((valid) => {
        if (valid) {
          formLoading.value = true
          delete formData.state
          // 调取子应用方法获取表单信息
          formData.questionnaireName = formData.questionnaireTitle
          formData.questJson = JSON.stringify(result)
          if (!type) {
            if(!formUpdate.value){
              saveForm(formData).then(res => {
                formLoading.value = false
                if (res.code == 200) {
                  inputDrawer.value = false
                  ElMessage({
                    message: '信息录入成功',
                    type: 'success'
                  })
                  getTableList()
                } else {
                  ElMessage({
                    message: res.msg,
                    type: 'error',
                    appendTo: document.querySelector('.jihua-submit')
                  })
                }
              }).catch(() => {
                formLoading.value = false
              })
            }
            else{
              updatePlaivist(formData).then(res => {
                formLoading.value = false
                if (res.code == 200) {
                  inputDrawer.value = false
                  ElMessage({
                    message: '信息录入成功',
                    type: 'success'
                  })
                  getTableList()
                } else {
                  ElMessage({
                    message: res.msg,
                    type: 'error',
                    appendTo: document.querySelector('.jihua-submit')
                  })
                }
              }).catch(() => {
                formLoading.value = false
              })
            }

          } else {
            // 是点击了提交按钮
            submitAuditForm(formData).then(result => {
              formLoading.value = false
              if (result.code == 200) {
                inputDrawer.value = false
                ElMessage({
                  message: '信息提交成功',
                  type: 'success'
                })
                getTableList()
              } else {
                ElMessage({
                  message: result.msg,
                  type: 'error',
                  appendTo: document.querySelector('.jihua-submit')
                })
              }
            }).catch(() => {
              inputDrawer.value = false
            })
          }
        }
      })
    }).catch((e) => {
      ElMessage({
        type: 'error',
        dangerouslyUseHTMLString: true,
        message: e,
        appendTo: '.jihua-submit'
      })
    })
  }
</script>

<style scoped lang="less">
  .title-desp {
    font-size: 18px;
    color: #666;
    font-weight: 700;
  }

  :deep(.my-label) {
    background: var(--el-color-success-light-9) !important;
  }

  .margin-top ::v-deep .el-descriptions__header {
    justify-content: center;
    font-size: 18px;
    font-weight: bold
  }

  .margin-top ::v-deep .el-descriptions__body .el-descriptions__table.is-bordered .el-descriptions__cell .el-form-item {
    margin-bottom: 0;
  }
</style>
